<template>
  <div>
    <h3>录音</h3>
    <div>
      <el-button type="primary" @click="recOpen">打开录音请求权限</el-button>
      <el-button type="primary" @click="recStart">开始录音</el-button>
      <el-button type="primary" @click="recStop">结束录音</el-button>
      <el-button type="primary" @clic="recPlay">本地试听</el-button>
    </div>
    <div>
      <div class="recwave"></div>
    </div>
  </div>
</template>

<script setup>
import Recorder from "recorder-core";
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
//录制wav格式的用这一句就行
//import 'recorder-core/src/engine/wav'

//可选的插件支持项，这个是波形可视化插件
import 'recorder-core/src/extensions/frequency.histogram.view'
import 'recorder-core/src/extensions/lib.fft'

// 录音实例
const rec = ref(null);
// 波形实例
const wave = ref(null);

const recOpen = () => {
  rec.value = Recorder({
    type: "mp3", //录音格式，可以换成wav等其他格式
    sampleRate: 16000, //录音的采样率，越大细节越丰富越细腻
    bitRate: 16, //录音的比特率，越大音质越好
    onProcess: onProcess
  });

  rec.value.open(() => {
    console.log("录音权限打开成功");
    // 创建音频可视化图形绘制对象
    wave.value = Recorder.FrequencyHistogramView({ elem: '.recwave' });
  });
};

// 录音过程
const onProcess = (
  buffers,
  powerLevel,
  bufferDuration,
  bufferSampleRate,
  newBufferIdx,
  asyncEnd
) => {
  //录音实时回调，大约1秒调用12次本回调
  //可实时绘制波形，实时上传（发送）数据
  if (wave.value)
    wave.value.input(
      buffers[buffers.length - 1],
      powerLevel,
      bufferSampleRate
    );
}

// 开始录音
const recStart = () => {
  rec.value.start();
}

// 停止录音
const recStop = () => {
  rec.value.stop((blob, duration) => {
    console.log(duration, blob)
    rec.value.close();
  });
}
</script>

<style scoped>
.recwave {
  width: 300px;
  height: 100px;
  border: 1px solid #000;
}
</style>
